"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.tableScroll = void 0;

var _react = _interopRequireWildcard(require("react"));

var _request = _interopRequireDefault(require("../request/request"));

var _useConnect = _interopRequireDefault(require("../context/useConnect"));

var _flexibleTable = _interopRequireDefault(require("./flexibleTable"));

var _filter = _interopRequireDefault(require("./components/filter2"));

require("./index.less");

var _events = _interopRequireDefault(require("../utils/events"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var paginationConfig = {
  showTotal: function showTotal(total, range) {
    return "\u7B2C ".concat(range[0], "-").concat(range[1], " \u6761/\u603B\u5171 ").concat(total, " \u6761");
  },
  showSizeChanger: true,
  current: 1,
  pageSize: 20,
  total: 0,
  pageSizeOptions: ['5', '10', '20', '50', '100']
};

var tableScroll = function tableScroll(columns) {
  if (!Array.isArray(columns)) {
    return;
  }

  return {
    x: 150 * columns.length
  };
};

exports.tableScroll = tableScroll;

var Index = function Index(props) {
  var filterRef = (0, _react.useRef)(null);
  var setPagination = (0, _react.useRef)(paginationConfig);

  var _useState = (0, _react.useState)(true),
      _useState2 = _slicedToArray(_useState, 2),
      loading = _useState2[0],
      setLoading = _useState2[1];

  var _useState3 = (0, _react.useState)([]),
      _useState4 = _slicedToArray(_useState3, 2),
      dataSource = _useState4[0],
      setDataSource = _useState4[1];

  var _useState5 = (0, _react.useState)({}),
      _useState6 = _slicedToArray(_useState5, 2),
      extra = _useState6[0],
      setExtra = _useState6[1];

  var _useState7 = (0, _react.useState)([]),
      _useState8 = _slicedToArray(_useState7, 2),
      queryOrderList = _useState8[0],
      setQueryOrderList = _useState8[1];

  var pagination = setPagination.current;

  var _useConnectSetting = (0, _useConnect.default)(['mutilModel']),
      mutilModel = _useConnectSetting.mutilModel; // 监听多标签属性的变化
  // 获取数据


  var getData = (0, _react.useCallback)( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
    var params,
        localParams,
        requestList,
        _args = arguments;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            params = _args.length > 0 && _args[0] !== undefined ? _args[0] : {};
            localParams = _objectSpread({}, params);
            setLoading(true);
            requestList = props.api ? [(0, _request.default)(props.api, {
              data: localParams
            })] : [];

            if (props.count) {
              requestList.push((0, _request.default)(props.count, {
                data: localParams
              }));
            }

            Promise.all(requestList).then(function (result) {
              var queryExtra = {};

              if (result[0].models) {
                if (props.preResult) {
                  var list = props.preResult(result[0].models, result[0].extra) || [];
                  setDataSource(list || []);
                } else {
                  setDataSource(result[0].models || []);
                }
              }

              if (result[0].extra) {
                queryExtra.extra = result[0].extra;
              }

              if (result[1]) {
                queryExtra.count = result[1].model || result[1].models;
              }

              if (result[0].pageInfo) {
                setPagination.current = _objectSpread(_objectSpread({}, paginationConfig), {}, {
                  pageSize: result[0].pageInfo.pageSize,
                  current: result[0].pageInfo.pageIndex,
                  total: result[0].pageInfo.total
                });
              }

              if (queryExtra.count) {
                setExtra(_objectSpread({}, queryExtra));
              } else {
                setExtra(_objectSpread({}, queryExtra.extra));
              }

              setLoading(false);
            }).catch(function (e) {
              setLoading(false);
            });

          case 6:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  })), [props.api]); // 翻页

  var onPageChange = (0, _react.useCallback)(function (paginationParams, filters, sorter) {
    var condition = filterRef.current && filterRef.current.getValues ? filterRef.current.getValues() : props.defaultCondition;
    var params = {
      condition: condition,
      pagingQuery: {
        pageIndex: paginationParams.current,
        pageSize: paginationParams.pageSize
      }
    };

    if (props.noPage) {
      delete params.pagingQuery;
    }

    if (sorter && sorter.order) {
      // 存在排序时
      params.queryOrderList = [{
        field: sorter.field,
        order: sorter.order === 'descend' ? 1 : 0
      }];
      setQueryOrderList(params.queryOrderList);
    } else {
      setQueryOrderList([]);
    } // todo 判断filters, 添加过滤条件


    getData(_objectSpread({}, params));
  }, [pagination, props.defaultCondition, getData, filterRef]);
  var onSearch = (0, _react.useCallback)(function () {
    onPageChange(_objectSpread(_objectSpread({}, pagination), {}, {
      current: 1
    }), undefined, queryOrderList.length > 0 ? queryOrderList[0] : {});
  }, [onPageChange]); // 页面初始化是
  // useEffect(() => {
  //   onSearch();
  // }, [props.defaultCondition]);
  // 多工作台，编辑页跳回首页，需要刷新列表页

  (0, _react.useEffect)(function () {
    var page = props.page;

    if (!page) {
      return;
    }

    if (mutilModel) {
      window.filterTemporary && (window.filterTemporary = undefined);
      return;
    }

    window.filterTemporary = window.filterTemporary || {};
    var pageName = window.filterTemporary.name;

    if (pageName === page && filterRef.current) {
      if (filterRef.current.formRef && filterRef.current.formRef.current) {
        var formRefTemp = filterRef.current.formRef.current;
        formRefTemp.setFieldsValue(_objectSpread({}, window.filterTemporary.value));
        setPagination.current && (setPagination.current.current = window.filterTemporary.pageIndex);
      }
    }

    return function () {
      if (!mutilModel && filterRef.current) {
        var _pageName = page;
        var temporary = filterRef.current.getValues && filterRef.current.getValues();
        var index = setPagination.current && setPagination.current.current;
        window.filterTemporary = window.filterTemporary || {};
        window.filterTemporary.name = _pageName;
        window.filterTemporary.value = temporary;
        window.filterTemporary.pageIndex = index;
      }
    };
  }, [mutilModel]); // 注册事件（多工作台，编辑页跳回首页，需要刷新列表页）

  (0, _react.useEffect)(function () {
    var page = props.page;

    if (!page) {
      return;
    }

    window.reload = window.reload || {};

    if (!window.reload[page]) {
      window.reload[page] = function () {
        _events.default.emit(page + '-reload');
      };
    }

    _events.default.on(page + '-reload', function () {
      var tableListRef = props.tableListRef;

      if (tableListRef.current && tableListRef.current.reload) {
        tableListRef.current.reload();
      }
    });

    return function () {
      if (window.reload[page]) {
        window.reload[page] = undefined;

        _events.default.removeListener(page + '-reload', function () {});
      }
    };
  }, []); // 放开对表格对控制

  (0, _react.useEffect)(function () {
    var userAction = {
      reload: function reload() {
        onPageChange(pagination, undefined, queryOrderList.length > 0 ? queryOrderList[0] : {});
      },
      reset: function reset() {},
      // clearSelected: () => {},
      getExtra: function getExtra() {
        return extra;
      },
      getList: function getList() {
        return dataSource;
      },
      filterRef: filterRef && filterRef.current
    };
    var tableListRef = props.tableListRef;

    if (tableListRef && typeof tableListRef !== 'function') {
      tableListRef.current = userAction;
    }
  }, [pagination, queryOrderList, onPageChange, extra, dataSource]);
  return /*#__PURE__*/_react.default.createElement("div", {
    className: "xuanyue-Table",
    style: {
      background: '#fff',
      padding: props.padding === 'none' ? 0 : 24
    }
  }, props.columnsFilter && /*#__PURE__*/_react.default.createElement(_filter.default, {
    type: props.page,
    onSearch: onSearch // onReset={()=>{}}
    ,
    columnsFilter: props.columnsFilter,
    defaultConditon: props.defaultCondition,
    ref: filterRef,
    submitPreMiddleware: props.submitPreMiddleware
  }), /*#__PURE__*/_react.default.createElement(_flexibleTable.default, {
    loading: loading,
    page: props.page,
    tableHeader: props.tableHeader,
    size: "middle",
    dataSource: dataSource,
    columns: props.columns,
    noPagination: props.noPagination,
    pagination: pagination,
    setPagination: setPagination,
    rowKey: props.rowKey || function (record) {
      return "".concat(record.id);
    },
    onChange: onPageChange,
    scroll: tableScroll(props.columns),
    rowSelection: props.rowSelection,
    columnsFilter: props.columnsFilter
  }));
};

var _default = _react.default.memo(Index);

exports.default = _default;